package com.ruoyi.chiwen.controller;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import java.util.Scanner;


import com.ruoyi.chiwen.controller.api.AuditApiController;
import com.ruoyi.chiwen.domain.TbStaging;
import com.ruoyi.chiwen.service.ITbStagingService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.chiwen.domain.TbAudit;
import com.ruoyi.chiwen.service.ITbAuditService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 审核Controller
 * 
 * @author chiwen
 * @date 2021-06-14
 */
@RestController
@RequestMapping("/chiwen/audit")
public class TbAuditController extends BaseController
{
    @Autowired
    private ITbAuditService tbAuditService;

    @Autowired
    private AuditApiController auditApiController;

    @Autowired
    private ITbStagingService tbStagingService;

    /**
     * 查询审核列表
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TbAudit tbAudit)
    {
        startPage();
        List<TbAudit> list = tbAuditService.selectTbAuditList(tbAudit);
        return getDataTable(list);
    }

    /**
     * 导出审核列表
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:export')")
    @Log(title = "审核", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TbAudit tbAudit)
    {
        List<TbAudit> list = tbAuditService.selectTbAuditList(tbAudit);
        ExcelUtil<TbAudit> util = new ExcelUtil<TbAudit>(TbAudit.class);
        return util.exportExcel(list, "审核数据");
    }

    /**
     * 获取审核详细信息
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:query')")
    @GetMapping(value = "/{aId}")
    public AjaxResult getInfo(@PathVariable("aId") Long aId)
    {
        return AjaxResult.success(tbAuditService.selectTbAuditById(aId));
    }

    /**
     * 新增审核
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:add')")
    @Log(title = "审核", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbAudit tbAudit)
    {
        tbAudit.setCreateTime(new Date());
        return toAjax(tbAuditService.insertTbAudit(tbAudit));
    }

    /**
     * 修改审核
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:edit')")
    @Log(title = "审核", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbAudit tbAudit)
    {
//        tbAudit1.getaStatus() 未修改前的审批状态    根绝 主键查询，只有一条数据
        TbAudit tbAudit1 = tbAuditService.selectTbAuditById(tbAudit.getaId());
//        从同意改为拒绝
        if(tbAudit1.getaStatus() == 1 && tbAudit.getaStatus() == 2){
            return AjaxResult.error("您已经同意，无法申请拒绝");
    }

//        如果修改前不是同意 ，并且本次修改为同意
        if(tbAudit1.getaStatus() != 1 && tbAudit.getaStatus() == 1){

            TbStaging tbStaging = new TbStaging();
            tbStaging.setUserId(tbAudit.getUserId());
            tbStaging.setaId(tbAudit.getaId());
            tbStaging.setaIsOverdue(0);
            tbStaging.setaOverdueDays(0);
            tbStaging.setaOverdueMoney(new BigDecimal(0));
            tbStaging.setaStatus(1);
//            当前期数   应还月份       应还金额
//            本金  利息

//            审批金额
            Long moneyNumber = tbAudit.getaMoneyNumber();
//            期数
            Long getaNper = tbAudit.getaNper();
//            本金
            double principal = moneyNumber / getaNper;
            BigDecimal principalBig = new BigDecimal(principal).setScale(2,BigDecimal.ROUND_HALF_UP);

            AjaxResult ajaxResult = auditApiController.calculateMoney(tbAudit.getaNper().intValue(),tbAudit.getaMoneyNumber());
            Object data = ajaxResult.get("data");
//            每月待还
            double monthMoney = Double.parseDouble(data.toString());
//            应还金额（本金+利息+逾期费用）
            tbStaging.setaAllMoney(new BigDecimal(monthMoney).setScale(2,BigDecimal.ROUND_HALF_UP));
//          利息
            BigDecimal lixi = new BigDecimal(monthMoney).subtract(principalBig).setScale(2,BigDecimal.ROUND_HALF_UP);

            tbStaging.setaPrincipal(principalBig);
            tbStaging.setaInterest(lixi);
//            获取当前月份
            int month = Calendar.getInstance().get(Calendar.MONTH)+1;
            for (int i = 1; i <= getaNper ; i++) {
//                当前期数
                tbStaging.setaNper(i + "-" + getaNper);
//                应还月份
                if(month == 12){
                    month = 0;
                }
                month = month+1;
                tbStaging.setaMonth(month);
                tbStagingService.insertTbStaging(tbStaging);
            }

        }
        return toAjax(tbAuditService.updateTbAudit(tbAudit));
    }

    /**
     * 删除审核
     */
    @PreAuthorize("@ss.hasPermi('chiwen:audit:remove')")
    @Log(title = "审核", businessType = BusinessType.DELETE)
	@DeleteMapping("/{aIds}")
    public AjaxResult remove(@PathVariable Long[] aIds)
    {
        return toAjax(tbAuditService.deleteTbAuditByIds(aIds));
    }

}
